package org.example.controllers;

import lombok.extern.slf4j.Slf4j;
import org.example.common.ApiResponse;
import org.example.common.NumberCheck;
import org.example.entitys.systems.User;
import org.example.service.inter.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description
 * @Author 魏锴
 * @Date 2023/11/25
 */
@Slf4j
@Controller
@ResponseBody
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/create")
    public ApiResponse createUser(User userVO) {
        log.info("createUser(" + userVO + ")");
        return userService.insertUser(userVO) ? ApiResponse.ok(userVO) : ApiResponse.failure();
    }

    @PostMapping("/query-id")
    public ApiResponse queryUserById(String id) {
        if (NumberCheck.isNotNumber(id)) return ApiResponse.paramIncorrect("id");
        log.info("queryUserById(id = " + id + ")");
        User userVO = userService.queryUserById(Integer.parseInt(id));
        return userVO != null ?
                ApiResponse.ok("查询结果", userVO) :
                ApiResponse.failure("数据库中不存在id = " + id + "的User");
    }

    @PostMapping("/query-name")
    public ApiResponse queryUserByName(String name) {
        log.info("queryUserByName(name = " + name + ")");
        User[] userVOs = userService.queryUserByName(name);
        return userVOs.length != 0 ?
                ApiResponse.ok("查询结果", userVOs) :
                ApiResponse.failure("数据库中不存在name = " + name + "的User");
    }
}
